<?php
namespace App\GraphQL\Mutations\Group;

use App\Models\Group;
use App\Models\GroupInspectionLog;
use App\Models\RepairerStatistical;
use GraphQL\Type\Definition\ResolveInfo;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Kra8\Snowflake\Snowflake;
use Nuwave\Lighthouse\Support\Contracts\GraphQLContext;

class Inspection
{

    public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
    {
        DB::transaction(function () use ($args) {
            $id = $args['id'];
            $data = $args['input'];
            $group = $this->validate($id, $data);
            $authUser = auth()->user();
            $inspectionlog = new GroupInspectionLog([
                'content' => $data['content'],
                'user_id' => $authUser
            ]);
            $group->inspection_logs()->create($inspectionlog);
            $devices = $group->devices;
            $logs = $devices->map(function ($item) use (&$authUser) {
                return [
                    'id' => resolve(Snowflake::class)->next(),
                    'level' => 'RED',
                    'user_id' => $authUser->id,
                    'device_id' => $item['id'],
                    'content' => '维护',
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now()
                ];
            });
            DB::table('device_logs')->insert($logs->toArray());
            // 更新施工方 维护次数
            $statistical = RepairerStatistical::firstOrCreate(['user_id'=>$authUser]);
            $statistical->increment('inspection_count');
        });

        return [
            'status' => '200',
            'message' => '更新成功'
        ];
    }

    public function validate($id, $data)
    {
        $rules = [
            'content' => [
                'required',
                'max:240'
            ]
        ];
        if ($data['cate'] == 'STAFF') {
            $rules['device_group_id'] = [
                'required',
                'integer'
            ];
        }
        $messages = [
            'content.required' => '巡检日志不能为空',
            'content.max' => '日志不能超过240字'
        ];
        $validate = Validator::make($data, $rules, $messages);
        if ($validate->fails()) {
            throw new \InvalidArgumentException($validate->messages()->first());
        }
        $old = Group::find($id);
        if (! $old) {
            throw new \Exception('群组不存在!');
        }
        return $old;
    }
}
